/*
 * @Description: 在线移交创建
 * @Author: Zzt
 * @Date: 2023-01-31 18:54:24
 * @LastEditTime: 2023-03-03 10:40:20
 */

import { EnumExportBusType, EnumReceiveTypes, receiveTypeName } from '@/dictionary/transfer';
import { createExportItem, ICreateExportParams } from '@/api/archives/export';
import { fetchMetadata } from '@/api/metadata';
import TransferTemplate from '@/components/TransferTemplate';
import { IMetadata } from '@/interfaces/metadata';
import { jsonClone } from '@/utils';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import { EnumTemplateTypes } from '@/view/system/TemplateManage/dictionaries';
import { Button, Form, Input, message, Modal, Select, Space } from 'antd';
import { useEffect, useState } from 'react';
import { ICommonDialog } from '@/interfaces/global';
import { IBaseProp } from '@/components/LevelTable';

const { Option } = Select;

interface IHandover extends ICommonDialog {
  info: IBaseProp;
  selectItems: number[];
  type: EnumReceiveTypes.Excel | EnumReceiveTypes.ZIP;
}
const HandoverTasks = (props: IHandover) => {
  const { visible, selectItems, info, type, onClose } = props;

  const [form] = Form.useForm();
  const onBuild = () => {
    form.submit();
  };

  // 元数据列表
  const [metadataList, setMetadataList] = useState<IMetadata[]>([]);

  useEffect(() => {
    if (visible) {
      // 请求当前层级元数据列表
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate: {
          atType: info.atType,
          atCode: info.atCode,
          level: info.level
        }
      };
      fetchMetadata(fieldQuery).then((res: any) => {
        const { data } = res;
        setMetadataList(data);
      });
    }
  }, [visible]);
  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    form.resetFields();
    onClose();
  };

  const onFinish = (val: any) => {
    const params: ICreateExportParams = jsonClone(val);
    params.exportType = type;
    params.fondsId = info.fondId;
    params.archiveTypeId = info.archiveTypeId;
    params.businessType = EnumExportBusType.Transfer;
    params.exportEntryInfo = {
      atCode: info.atCode,
      atType: info.atType,
      level: info.level,
      entryIdList: selectItems,
      searchCondition: '',
      dbName: info.dbName
    };
    params.exportOriginalRule.level = info.level;

    createExportItem(params).then(() => {
      message.success('移交任务创建成功');
      onCancel();
    });
  };

  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      title={`${receiveTypeName(type)}移交`}
      footer={[
        <Button key={'close'} onClick={() => onClose()}>
          取消
        </Button>,
        <Button key={'submit'} type="primary" onClick={() => onBuild()}>
          创建
        </Button>
      ]}
    >
      <Form form={form} onFinish={onFinish}>
        <Form.Item label={'已选择条目'} required>
          {selectItems.length}条
        </Form.Item>
        <Form.Item label={'档案类型'} required>
          {info.atName}
        </Form.Item>
        <Form.Item label={'移交任务名称'} name={'name'} rules={[{ required: true }]}>
          <Input placeholder="请填写移交任务名称" />
        </Form.Item>
        <Form.Item
          name="templateId"
          label="模板配置"
          extra="请选择档案导出条件模板，规则模板可在“模板设计”内配置)"
          rules={[{ required: true, message: '请选择模板' }]}
        >
          <TransferTemplate tplType={EnumTemplateTypes.ExcelExport} />
        </Form.Item>
        <Form.Item
          label="电子原文导出配置"
          extra="根据配置解析字段（一般为文件档号）层次，并在系统执行导出时生成文件夹层级，相关电子文件放置在最后一个文件夹内。"
        >
          <Space>
            <Form.Item
              name={['exportOriginalRule', 'fieldName']}
              rules={[{ required: true, message: '请选择字段' }]}
              noStyle
            >
              <Select style={{ width: 140 }}>
                {metadataList.map((metadata: IMetadata) => (
                  <Option key={metadata.id} value={metadata.field_name}>
                    {metadata.field_desc}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item noStyle>匹配分割符</Form.Item>
            <Form.Item
              name={['exportOriginalRule', 'concatMark']}
              rules={[{ required: true, message: '请输入分隔符' }]}
              noStyle
            >
              <Input style={{ width: 60 }} />
            </Form.Item>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default HandoverTasks;
